<template>
  <el-dialog
    :title="formData.id ? '编辑筒仓' : '新增筒仓'"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="800px"
    :before-close="handleClose" draggable>
    
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px">
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="筒仓编码" prop="siloCode">
            <el-input
              v-model="formData.siloCode"
              placeholder="请输入筒仓编码"
              :disabled="!!formData.id" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="筒仓名称" prop="siloName">
            <el-input
              v-model="formData.siloName"
              placeholder="请输入筒仓名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12" v-if="false">
          <el-form-item label="物料编码" prop="materCode">
            <el-input
              v-model="formData.materCode"
              placeholder="请输入物料编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料名称" prop="materName">
            <el-select
              v-model="formData.materName"
              placeholder="请选择物料"
              style="width: 100%"
              clearable
              filterable
              @change="handleMaterChange"
            >
              <el-option
                v-for="item in materOptions"
                :key="item.id"
                :label="item.materName"
                :value="item.materName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="额定容量" prop="capacityQty">
            <el-input
              v-model.number="formData.capacityQty"
              placeholder="请输入额定容量"
              type="number"
              step="0.01" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="最低安全库存" prop="minStockQty">
            <el-input
              v-model.number="formData.minStockQty"
              placeholder="请输入最低安全库存"
              type="number"
              step="0.01" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高安全库存" prop="maxStockQty">
            <el-input
              v-model.number="formData.maxStockQty"
              placeholder="请输入最高安全库存"
              type="number"
              step="0.01" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        
        <el-col :span="12">
          <el-form-item label="仓库名称" prop="warehouseName">
            <el-input
              v-model="formData.warehouseName"
              placeholder="请输入仓库名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="库位名称" prop="locationName">
            <el-input
              v-model="formData.locationName"
              placeholder="请输入库位名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="false">
        <el-col :span="12">
          <el-form-item label="库位ID" prop="locationID">
            <el-input
              v-model="formData.locationID"
              placeholder="请输入库位ID" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="仓库ID" prop="warehouseID">
            <el-input
              v-model="formData.warehouseID"
              placeholder="请输入仓库ID" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="单位" prop="unit">
            <el-input
              v-model="formData.unit"
              placeholder="请输入单位" />
          </el-form-item>
        </el-col>
        
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="容积(m³)" prop="capacityvolumeM3">
            <el-input
              v-model.number="formData.capacityvolumeM3"
              placeholder="请输入容积"
              type="number"
              step="0.01" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio label="10">启用</el-radio>
              <el-radio label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>



      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="补货点" prop="reorderPointQty">
            <el-input
              v-model="formData.reorderPointQty"
              placeholder="请输入补货点" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="安装日期" prop="installDate">
            <el-date-picker
              v-model="formData.installDate"
              type="date"
              placeholder="选择安装日期"
              style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="制造商" prop="manufacturer">
            <el-input
              v-model="formData.manufacturer"
              placeholder="请输入制造商" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="型号" prop="model">
            <el-input
              v-model="formData.model"
              placeholder="请输入型号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="出厂编号" prop="serialNo">
        <el-input
          v-model="formData.serialNo"
          placeholder="请输入出厂编号" />
      </el-form-item>

      <el-form-item label="备注" prop="remarks">
        <el-input
          v-model="formData.remarks"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
          maxlength="500"
          show-word-limit />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">
        {{ formData.id ? '更新' : '创建' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { request } from '@/utils/request'
// 定义 props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({})
  }
})

// 定义 emits
const emit = defineEmits(['update:visible', 'submit', 'close'])

// 响应式数据
const loading = ref(false)
const formRef = ref()
const materOptions = ref([]) // 物料选项列表
// 表单验证规则
const formRules = {
  materName:[
    { required: true, message: '请选择物料名称', trigger: 'blur' },
  ],
  siloCode: [
    { required: true, message: '请输入筒仓编码', trigger: 'blur' },
    { min: 1, max: 50, message: '筒仓编码长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  siloName: [
    { required: true, message: '请输入筒仓名称', trigger: 'blur' },
    { min: 1, max: 100, message: '筒仓名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  minStockQty: [
    { required: true, message: '请输入最低安全库存', trigger: 'blur' }
  ],
  maxStockQty: [
    { required: true, message: '请输入最高安全库存', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  capacityQty: [
    { required: true, message: '请输入额定容量', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的数字格式', trigger: 'blur' }
  ],
  capacityvolumeM3: [
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的数字格式', trigger: 'blur' }
  ],
  minStockQty: [
    { required: true, message: '请输入最低安全库存', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的数字格式', trigger: 'blur' }
  ],
  maxStockQty: [
    { required: true, message: '请输入最低安全库存', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的数字格式', trigger: 'blur' }
  ]
}

// 加载物料列表
const loadMaterList = async () => {
  try {
    const response = await request.get('/MaterInfo')
    materOptions.value = response || []
  } catch (error) {
    ElMessage.error('加载物料列表失败')
    materOptions.value = []
  }
}
// 监听 visible 变化，重置表单验证
watch(() => props.visible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    })
    // 打开弹窗时加载物料列表
    loadMaterList()
  }
})
// 物料选择变化处理
const handleMaterChange = (value) => {
  const selectedMater = materOptions.value.find(item => item.materName === value)
  if (selectedMater) {
    // 自动填充物料编码
    props.formData.materCode = selectedMater.materCode
  }
}
// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}

// 提交表单
const handleSubmit = async () => {
  debugger;
  if (!formRef.value) return
  
  try {
    // 表单验证
    await formRef.value.validate()
    
    loading.value = true
    // 创建表单数据的副本，避免直接修改props
    // const submitData = JSON.parse(JSON.stringify(props.formData))
    
    // // 遍历所有字段，将null值转换为空字符串
    // Object.keys(submitData).forEach(key => {
    //   if (submitData[key] === '') {
    //     submitData[key] = null
    //   }
    // })
    // 触发提交事件，传递表单数据
    emit('submit',  {...props.formData}  )
    
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    }
  } finally {
    loading.value = false
  }
}

// 暴露方法给父组件
defineExpose({
  setLoading: (value) => {
    loading.value = value
  }
})
</script>

<style scoped>
/* 弹窗样式优化 */
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>